from ..base import PermissionRuleHandler, register_handler

@register_handler("field_not_like")
class FieldNotLikeHandler(PermissionRuleHandler):
    """
    字段模糊不匹配处理器 (NOT LIKE)
    - user_field: 用户信息中的字段名
    - target_field: 数据库表中的字段名
    - 生成SQL: table.target_field NOT LIKE '%user_value%'
    """
    def get_required_config_keys(self):
        return ["user_field", "target_field"]

    def validate_config(self, config):
        return all(k in config for k in self.get_required_config_keys())

    def generate_sql(self, table_alias: str, config: dict, user: dict) -> str:
        user_field = config["user_field"]
        target_field = config["target_field"]
        user_val = user.get(user_field)

        # NOT LIKE 操作通常针对字符串，如果值不存在或不是字符串，则认为不应用此规则 (全权限)
        if not isinstance(user_val, str) or not user_val:
            return "1=1"
        
        # 对值进行转义，防止SQL注入
        escaped_val = user_val.replace("'", "''")
        
        result = f"{table_alias}.{target_field} NOT LIKE '%{escaped_val}%'"
        return result